package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.Ability;
import it.polimi.swimv2.entities.Suggestion;
import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.exception.AbilityExistsException;
import it.polimi.swimv2.exception.SuggestionException;
import it.polimi.swimv2.remote.SuggestionManagerRemote;

import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class SuggestionManager
 */
@Stateless
public class SuggestionManager implements SuggestionManagerRemote {
	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;

	/**
	 * Default constructor.
	 */
	public SuggestionManager() {

	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Suggestion> getSuggestion() {
		Query q = em.createQuery("SELECT OBJECT(s) FROM Suggestion s");
		return q.getResultList();
	}

	@Override
	public void sendSuggestion(String sender, String newAbility) throws SuggestionException, AbilityExistsException {
		User user = em.find(User.class, sender);
		if (user == null ||!isValid(newAbility)){
			throw new SuggestionException();
		}
		if (alreadyExists(newAbility)){
			throw new AbilityExistsException();
		}
		Suggestion sug = new Suggestion();
		sug.setNewAbility(newAbility);
		sug.setSender(user);
		em.persist(sug);
		return;
	}

	private boolean isValid(String newAbility) {
		
		return (newAbility!=null&&newAbility.length()>0);
	}

	private boolean alreadyExists(String newAbility) throws SuggestionException {
		Query q=em.createQuery("SELECT OBJECT(a) FROM Ability a");
		@SuppressWarnings("unchecked")
		List<Suggestion> declarableAbilities=q.getResultList();
		for(Object ab:declarableAbilities){
			if(((Ability)ab).getName().equalsIgnoreCase(newAbility)){
				return true;
			}
		}
		return false;
	}

	@Override
	public void acceptSuggestion(Integer id) {
		Suggestion sug = em.find(Suggestion.class, id);
		Ability existingAb = em.find(Ability.class, sug.getNewAbility());
		if (sug != null) {
			if (existingAb == null) {
				Ability a = new Ability(sug.getNewAbility());
				em.persist(a);
			}
			em.remove(sug);
		}
	}

	@Override
	public void refuseSuggestion(Integer id) {
		Suggestion sug = em.find(Suggestion.class, id);
		if (sug != null) {
			em.remove(sug);
		}
	}

}
